

package com.hazelcast.scheduledexecutor.impl;

import com.hazelcast.core.ManagedContext;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.services.NodeAware;
import com.hazelcast.partition.PartitionAware;
import com.hazelcast.scheduledexecutor.NamedTask;
import com.hazelcast.scheduledexecutor.StatefulTask;

import java.util.Map;

public class ScheduledRunnableAdapter<V> extends AbstractTaskDecorator<V> implements NodeAware, PartitionAware, NamedTask, StatefulTask {

    public ScheduledRunnableAdapter() {
    }

    public ScheduledRunnableAdapter(Runnable task) {
        super(task);
    }

    public Runnable getRunnable() {
        return (Runnable) delegate;
    }

    public void setRunnable(Runnable runnable) {
        delegate = runnable;
    }

    @Override
    public V call() throws Exception {
        ((Runnable) delegate).run();
        return null;
    }

    @Override
    public Object getPartitionKey() {
        if (delegate instanceof PartitionAware aware) {
            return aware.getPartitionKey();
        }
        return null;
    }

    @Override
    public void setNode(Node node) {
        ManagedContext managedContext = node.getSerializationService().getManagedContext();
        delegate = managedContext.initialize(delegate);
    }

    @Override
    public String getName() {
        if (delegate instanceof NamedTask task) {
            return task.getName();
        }
        return null;
    }

    @Override
    public void save(Map snapshot) {
        if (delegate instanceof StatefulTask task) {
            task.save(snapshot);
        }
    }

    @Override
    public void load(Map snapshot) {
        if (delegate instanceof StatefulTask task) {
            task.load(snapshot);
        }
    }

    @Override
    public int getClassId() {
        return ScheduledExecutorDataSerializerHook.RUNNABLE_ADAPTER;
    }

    @Override
    public String toString() {
        return "ScheduledRunnableAdapter" + "{task=" + delegate + '}';
    }

}
